package cn.dw.web.action;

import java.io.BufferedReader;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.FileReader;
import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import com.google.gson.JsonElement;
import com.google.gson.JsonObject;
import com.google.gson.JsonParser;

import cn.dw.domain.MusicInfo;
import cn.dw.service.MusicService;
import net.sf.json.JSONObject;


public class musicGetting {
	
	public static void main(String[] args) {
		try {
//			QQMusic();
//			System.out.println(QQMusic());
		} catch (Exception e) {
			// TODO 自动生成的 catch 块
			e.printStackTrace();
		}
	}
	
	private MusicService ms;
	
	public JSONObject result;
	
	@SuppressWarnings("unused")
	public String Music() throws Exception {

		String SongMid = "";
		String FileName = "";
		
		List<MusicInfo> musics = ms.getAll();
//		List<Map<String, Object>> list = new ArrayList<Map<String,Object>>();
//		
//		Map<String, Object> map;
//		
//		int count = musics.size();
//		
//		for (int i = 0; i < count; i++) {
//			
//			map = new HashMap<String, Object>();
//			MusicInfo music = musics.get(i);
//			String playUrl = "";
//			if(music.getType().equals("qqmusic")){
//				playUrl = "http://dl.stream.qqmusic.qq.com/"
//						+ "FileName?"
//						+ "vkey=VKey"
//						+ "&guid=4751879078&uin=0&fromtag=66";
//
//				SongMid = music.getSongMid();
//				FileName = music.getFileName();
//				String filepath = QQMusicFileGet(SongMid, FileName);
//				
//				String VKey = getVkey(filepath);
//				playUrl = playUrl.replace("FileName", FileName).replace("VKey", VKey);
//				
//			} else if (music.getType().equals("xiami")) {
//				playUrl = music.getPlayUrl();
//			} else {
//				
//			}
//
//			map.put("name", music.getSongName());
//			map.put("playUrl", playUrl);
//			
//			list.add(map);
//			
//		}
		
//		map = new HashMap<String, Object>();
//		
//		map.put("list", list);
		
		Map<String, List<MusicInfo>> map2 = new HashMap<String, List<MusicInfo>>();
		
		map2.put("list", musics);
		
			
		JSONObject json = JSONObject.fromObject(map2);
		
		this.result = json;
		
		System.out.println(result);
		
		return "MusicInfo";
	}
	
	public static String QQMusicFileGet(String SongMid, String FileName) throws Exception {

		String vkey_url = "https://c.y.qq.com/base/fcgi-bin/fcg_music_express_mobile3.fcg?"
				+ "g_tk=5381&jsonpCallback=MusicJsonCallback4226492037049694&"
				+ "loginUin=0&hostUin=0&format=json&inCharset=utf8&outCharset=utf-8"
				+ "&notice=0&platform=yqq&needNewCode=0&cid=205361747"
				+ "&callback=MusicJsonCallback4226492037049694&uin=0"
				+ "&songmid=SongMid&filename=FileName&guid=4751879078";
		
		vkey_url = vkey_url.replace("SongMid", SongMid).replace("FileName", FileName);
		
		URL url = new URL(vkey_url);
    	
    	HttpURLConnection conn = (HttpURLConnection)url.openConnection();  
    	
    	//防止屏蔽程序抓取而返回403错误
        conn.setRequestProperty("User-Agent", "Mozilla/4.0 (compatible; MSIE 5.0; Windows NT; DigExt)");

     //   URI uri = new URI(url_);
        
        String path = "C:\\local\\";
        
        //得到输入流
        InputStream inputStream = conn.getInputStream();  
        
        byte[]  getData = readInputStream(inputStream);
        
        File saveDir = new File(path);
        
        if(!saveDir.exists()){
            saveDir.mkdir();
        }
        
        File file = new File(path+"123.txt");
        
        FileOutputStream fos = new FileOutputStream(file);
        
        fos.write(getData);
        
        if(fos!=null){
            fos.close();  
        }
        if(inputStream!=null){
            inputStream.close();
        }
        
        return "C:\\local\\123.txt";
	}
	
	@SuppressWarnings("unused")
	private static String getVkey(String path) {
		
		
		File file = new File(path);
		
		String json = txt2String(file);
		
		json = json.substring(json.indexOf("(")+1, json.length()-1);
		
		JsonParser jp = new JsonParser();
		
		JsonElement je = jp.parse(json);
		
		JsonObject jo = je.getAsJsonObject();
		
		je = jo.get("data");
		
		jo = je.getAsJsonObject();
		
		je = jo.get("items");
		
		je = jp.parse(je.toString().substring(1, je.toString().length()-1));
		
		jo = je.getAsJsonObject();
		
		je = jo.get("vkey");
		
//		System.out.println(je.toString().substring(1, je.toString().length()-1));
		
		String vkey = je.toString().substring(1, je.toString().length()-1);
		
		return vkey;
		
	}

	
	 public static String txt2String(File file){
	        StringBuilder result = new StringBuilder();
	        try{
	            BufferedReader br = new BufferedReader(new FileReader(file));//构造一个BufferedReader类来读取文件
	            String s = null;
	            while((s = br.readLine())!=null){//使用readLine方法，一次读一行
	                result.append(System.lineSeparator()+s);
	            }
	            br.close();    
	        }catch(Exception e){
	            e.printStackTrace();
	        }
	        return result.toString();
	    }
	
	 public static  byte[] readInputStream(InputStream inputStream) throws IOException {  
	        byte[] buffer = new byte[1024];  
	        int len = 0;  
	        ByteArrayOutputStream bos = new ByteArrayOutputStream();  
	        while((len = inputStream.read(buffer)) != -1) {  
	            bos.write(buffer, 0, len);  
	        }  
	        bos.close();  
	        return bos.toByteArray();  
	    }

	public MusicService getMs() {
		return ms;
	}

	public void setMs(MusicService ms) {
		this.ms = ms;
	}

	public JSONObject getResult() {
		return result;
	}

	public void setResult(JSONObject result) {
		this.result = result;
	}
}
